//
//  SXCustomNavigationController.m
//  SXDataManager-SXDataManager
//
//  Created by wangshuixin on 2019/1/25.
//

#import "SXCustomNavigationController.h"
#import <objc/runtime.h>

@interface SXCustomNavigationController ()<UIGestureRecognizerDelegate>

@end

@implementation SXCustomNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 手势代理
    self.interactivePopGestureRecognizer.delegate = self;
    // 设置导航栏样式
    [self configNavigationBarStyle];
}

// 设置导航栏样式
-(void)configNavigationBarStyle {
    [self.navigationBar setBarTintColor:[UIColor colorWithRed:0x35/255.0 green:0x35/255.0 blue:0x35/255.0 alpha:1.0]];
    [self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:18]}];
}


// 决定是否触发手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // 排除根控制器，其他所有子控制器都要触发手势
    return self.childViewControllers.count > 1;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
// 重写导航控制器的push方法
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 在push之前，统一设计返回按钮
    // 只有非根控制才需要设置
    if (self.childViewControllers.count > 0) {
        
        // 创建按钮
        UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        leftButton.frame = CGRectMake(0, 0, 60, 30);
        [leftButton addTarget:self action:@selector(respondToBackEvent) forControlEvents:UIControlEventTouchUpInside];
        [leftButton setTitle:@" 返回" forState:UIControlStateNormal];
        [leftButton setImage:[[NSClassFromString(@"SXGetBundleData") performSelector:@selector(SXImageName:) withObject:@"icon_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        // 修改导航栏左边的item
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        // 隐藏tabbar
        viewController.hidesBottomBarWhenPushed = YES;
    }
    
    // 跳转
    // 调用父类
    [super pushViewController:viewController animated:animated];
}
#pragma clang diagnostic pop

- (void)respondToBackEvent {
    // 导航控制器返回
    [self popViewControllerAnimated:YES];
}

@end
